import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Setting } from './setting.entity';
import DataBase from 'src/config/database';

@Injectable()
export class SettingService {
  constructor(
    @InjectRepository(Setting)
    private settingRepository: Repository<Setting>,
  ) {}

  findAll(): Promise<Setting[]> {
    return this.settingRepository.find();
  }

  findOne(id: number): Promise<Setting> {
    return this.settingRepository.findOne({where:{id}});
  }

  findOne_by_key(key: string): Promise<Setting> {
    return this.settingRepository.findOne({where:{key}});
  }

  findOne_by_key_all(key: string): Promise<Setting[]> {
    return this.settingRepository.find({where:{key: key},order: {id: 'asc'}});
  }

  async remove(id: number): Promise<void> {
    await this.settingRepository.delete(id);
  }

  async create(shieId: Setting): Promise<void> {
    await this.settingRepository.save(shieId);
  }

  async update(shieId: Setting): Promise<void> {
    await this.settingRepository.save(shieId);
  }

  async set_auth_list(key: string, list: string[]): Promise<string> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
     
      await this.settingRepository.createQueryBuilder(null, queryRunner).delete().where({key: key}).execute()
      let settingList = []
      list.map(e => {
        let setting = new Setting()
        setting.key = key
        setting.value = e
        settingList.push(setting)
      })
      await this.settingRepository.createQueryBuilder(null, queryRunner).insert().into(Setting).values(settingList).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
}
